# -*- coding: utf-8 -*-
"""
333333333

22222222222

1111111

Created on Mon May 27 16:56:16 2019

@author: 10946
"""

from math import ceil

import pymysql
from spider import Spider

class Film:
    
    host = 'https://www.subo8988.com'
    
    def split_info(self, info_str):
        if '/' in info_str:
            info_str = info_str.split('/')
        elif ',' in info_str:
            info_str = info_str.split(',')
        elif ' ' in info_str:
            info_str = info_str.split(' ')
        else:
            info_str = [info_str]
        return [i.strip() for i in info_str if i != '']
    
    def get_film_info(self, url, encoding = None):
        regex = dict(
                intro ='<div class="vodplayinfo">(.*?)</div>',
                name = '<h2>(.*?)</h2>\s+?<span>(.*?)</span>\s+?<label>(.*?)</label>',
                info = '\
<li>别名：<span>(.*?)</span></li>\s+?\
<li>导演：<span>(.*?)</span></li>\s+?\
<li>主演：<span>(.*?)</span></li>\s+?\
<li>类型：<span>(.*?)</span></li>\s+?\
<li class="sm">地区：<span>(.*?)</span></li>\s+?\
<li class="sm">语言：<span>(.*?)</span></li>\s+?\
<li class="sm">上映：<span>(.*?)</span></li>\s+?\
<li class="sm">片长：<span>(.*?)</span></li>\s+?\
<li class="sm">更新：<span>(.*?)</span></li>\s+?\
<li class="sm">总播放量：<span><em id="hits">.*?</script></span></li>\s+?\
<li class="sm">今日播放量：<span>(.*?)</span></li>\s+?\
<li class="sm">总评分数：<span>(.*?)</span></li>\s+?\
<li class="sm">评分次数：<span>(.*?)</span></li>',
                show_list = 'checked="" />(.*?)</li>'
                )
        info = Spider().get_info(url,encoding = encoding,**regex)
        director = self.split_info(info['info'][0][1])
        actor = self.split_info(info['info'][0][2])
        types = self.split_info(info['info'][0][3])
        area = self.split_info(info['info'][0][4])
        language = self.split_info(info['info'][0][5])
        
        film_info = dict(
                name = info['name'][0][0],
                name_info = info['name'][0][1],
                grader = info['name'][0][2],
                another_name = info['info'][0][0],
                director = director,
                actor = actor,
                types = types,
                area = area,
                language = language,
                show_time = info['info'][0][6],
                lenth = info['info'][0][7],
                update_time = info['info'][0][8],
                day_palys = info['info'][0][9],
                total_score = info['info'][0][10],
                total_score_number = info['info'][0][11],
                m3u8_list = [i for i in info['show_list'] if i.endswith('index.m3u8')],
                yun_list = [i for i in info['show_list'] if not i.endswith('index.m3u8')]
                )
        return film_info
    
    #关键字查询
    def film_search(self, keyword, encoding = None):
        post_url = 'https://www.subo8988.com/index.php?m=vod-search'
        data = {
                'wd': keyword,
                'submit': 'search'
                }
        regex = dict(
                info = '<li><span class="tt"></span><span class="xing_vb4"><a href="(.*?)" target="_blank">(.*?)</a></span> <span class="xing_vb5">(.*?)</span> <span class="xing_vb[67]">(.*?)</span></li>'
                )
        info = Spider().post_info(post_url,data,**regex)
        info = [{'url':self.host+i[0],'name':i[1],'types':i[2],'update_time':i[3]} for i in info['info']]
        return {'':info}
    search_word
    
    #获取所有的url
    def get_all_show_page(self):
        url = 'https://www.subo8988.com/'
        join_url = 'https://www.subo8988.com/?m=vod-index-pg-{}.html'
        regex = dict(
                page = '<div class="pages" style="margin-bottom:10px;">共(.*?)条数据&nbsp;'
                )
        count = Spider().get_info(url,**regex)
        page = ceil(int(count['page'][0])/50)
        return [join_url.format(i) for i in range(1,page+1)]
    
    #传入对于类型的url,返回所有的影片
    def get_show_page_info(self,url):
#        url = 'https://www.subo8988.com/?m=vod-type-id-5.html'
        regex = dict(
                page = '<div class="pages" style="margin-bottom:10px;">共(.*?)条数据&nbsp;',
                types ='''<dd><a href='/'>首页</a>&nbsp;&nbsp;&raquo;&nbsp;&nbsp;<a href='.*?' >(.*?)</a></dd>'''
                )
        join_url = url.split('.html')[0]+'-pg-{}'+'.html'
        count = Spider().get_info(url,**regex)
        page = ceil(int(count['page'][0])/50)
        urls = [join_url.format(i) for i in range(1,page+1)]
        s = Spider()
        film_list = []
        regex2 = dict(
                info = '<li><span class="tt"></span><span class="xing_vb4"><a href="(.*?)" target="_blank">(.*?)</a></span> <span class="xing_vb5">(.*?)</span> <span class="xing_vb[67]">(.*?)</span></li>'
                    )
        for i in urls[0:5]:
            info1 = s.get_info(i,**regex2)
            info1 = [{'url':self.host+i[0],'name':i[1],'types':i[2],'update_time':i[3]} for i in info1['info']]
            film_list.extend(info1)
        return {'type_name':count['types'][0],'film_list':film_list}
    
    #存入mysql
    def save_all_film_info(self,info):
        db = pymysql.connect('localhost','root','','film')
        cursor = db.cursor()
        sql = 'insert into film_info(name,url,type,update_time) values (?,?,?,?)'
        insert_list = [(i['name'],i['url'],i['types'],i['update_time']) for i in info['search_word']]
        try:
            cursor.executemany(sql,insert_list)
            db.commit()
        except:
                print('出错了')
                db.rollback()
        '''
        插入数据不能迭代，能用批量一定要批量
        for i in info['search_word'][0:1]:
            print(list(i.values()),type(i.values()))
            try:
                cursor.execute(sql,[i['name'],i['url'],i['types'],i['update_time']])
                db.commit()
            except:
                print('出错了')
                db.rollback()
        '''
                
    #获取每页数据
    def get_all_page(self,url):
        regex = dict(
                info = '<li><span class="tt"></span><span class="xing_vb4"><a href="(.*?)" target="_blank">(.*?)</a></span> <span class="xing_vb5">(.*?)</span> <span class="xing_vb[67]">(.*?)</span></li>'
                )
        info = Spider().get_info(url,**regex)['info']
        info = [{'url':self.host+i[0],'name':i[1],'types':i[2],'update_time':i[3]} for i in info]
        return {'page_info':info}


if __name__ == '__main__':
    url = 'https://www.subo8988.com/?m=vod-detail-id-25296.html'
    x = Film()
#    info = x.get_film_info(url)
    info2 = x.film_search('火影')
#    urls =x.get_all_show_page()
    x.save_all_film_info(info2)
